﻿using System;
using System.Linq;
using System.Text;

namespace UtilZ.Dotnet.Ex.Base
{
    /// <summary>
    /// Encoding扩展方法
    /// </summary>
    public class EncodingEx
    {
        static EncodingEx()
        {
#if CORE
            //注册之后才可使用GBK编码
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
#endif
        }

        /// <summary>
        /// 获取指定codepage值的Encoding,失败抛出异常
        /// </summary>
        /// <param name="codepage">codepage值</param>
        /// <returns>Encoding</returns>
        public static Encoding GetEncodingByCodepage(int codepage)
        {
            return Encoding.GetEncoding(codepage);
        }

        /// <summary>
        /// 获取指定名称的Encoding,失败抛出异常
        /// </summary>
        /// <param name="name">编码名称</param>
        /// <returns>Encoding</returns>
        public static Encoding GetEncodingByName(string name)
        {
            if (string.Equals(name, "utf8", StringComparison.OrdinalIgnoreCase))
            {
                name = "utf-8";
            }

            return Encoding.GetEncoding(name);
        }

        /// <summary>
        /// 获取指定名称或codepage值的Encoding,失败抛出异常
        /// </summary>
        /// <param name="cncodingStr">编码名称或codepage值</param>
        /// <returns>Encoding</returns>
        public static Encoding GetEncoding(string cncodingStr)
        {
            Encoding encoding;
            int codepage;
            if (int.TryParse(cncodingStr, out codepage))
            {
                encoding = GetEncodingByCodepage(codepage);
            }
            else
            {
                encoding = GetEncodingByName(cncodingStr);
            }

            return encoding;
        }

        /// <summary>
        /// 获取当前支持的所有编码信息
        /// </summary>
        /// <returns>当前支持的所有编码信息</returns>
        public static string GetAllEncodingInfo()
        {
            //var eeee = EncodingEx.GetEncoding("IBM037");
            // var ret = sizeof(char);
            EncodingInfo[] es = Encoding.GetEncodings().OrderBy(t => { return t.Name; }).ToArray();
            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"{"Name",-40}{"DisplayName",-40}{"CodePage",-20}{"EncodingName"}");
            foreach (var e in es)
            {
                sb.AppendLine($"{e.Name,-40}{e.DisplayName,-40}{e.CodePage,-20}{e.GetEncoding().EncodingName}");
            }
            return sb.ToString();
        }
    }
}
